/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.lidovky.articles.cli;

import cz.mzk.lidovky.articles.PropertyNames;
import cz.mzk.lidovky.articles.krameriusAccess.Repository;
import cz.mzk.rehan.commons.Dom4jUtils;
import cz.mzk.rehan.commons.PropertyLoader;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;

/**
 * Saves errors revealed in periodical in repository into file defined in properties
 * @author Martin Řehánek (rehan@mzk.cz)
 */
class SaveRepositoryErrors implements Action {

    private static final Logger logger = Logger.getLogger(SaveRepositoryErrors.class.getName());
    private final File logDir;
    private final PropertyLoader properties;

    public SaveRepositoryErrors(PropertyLoader properties) {
        String logDirFilename = properties.loadString(PropertyNames.REPOSITORY_ERRORS_LOG_DIR);
        logDir = new File(logDirFilename);
        this.properties = properties;
    }

    @Override
    public void run() {
        String dateStr = (new LocalDate()).toString("YYYY-dd-MM");
        String timeStr = (new LocalTime()).toString("HH:mm:ss");
        StringBuilder filename = new StringBuilder();
        filename.append(logDir.getAbsolutePath()).append(File.separator);
        filename.append(dateStr).append('_').append(timeStr).append(".log.xml");
        File errorsFile = new File(filename.toString());
        logger.log(Level.INFO, "saving errors in repository into: ''{0}''", errorsFile.getAbsolutePath());
        Document errorsInRepository = Repository.instanceOf(properties).getErrorsInRepository();
        Dom4jUtils.saveDocument(errorsInRepository, errorsFile);
    }
}
